﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TaskTestWPF.ViewModels
{
    public class MainWindowViewModel : BindableBase
    {
        /// <summary>
        /// 取消任务时使用
        /// </summary>
        private CancellationTokenSource tokenSource = new CancellationTokenSource();

        /// <summary>
        /// 暂停继续
        /// </summary>
        private ManualResetEvent resetEvent = new ManualResetEvent(true);

        private bool _isRunning = false;
        public bool IsRunning  
        {
            get { return _isRunning; }
            set { SetProperty(ref _isRunning, value); }
        }

        private string _taskRunConent = "...";
        public string TaskRunConent
        {
            get { return _taskRunConent; }
            set { SetProperty(ref _taskRunConent, value); }
        }


        public DelegateCommand RunCommand { get; set; }
        public DelegateCommand PauseCommand { get; set; }
        public DelegateCommand CancelCommand { get; set; }

        public DelegateCommand ContinueCommand { get; set; }

        public MainWindowViewModel()
        {
            RunCommand = new DelegateCommand(Run);
            PauseCommand = new DelegateCommand(Pause);
            CancelCommand = new DelegateCommand(Cancel);
            ContinueCommand = new DelegateCommand(Continue);
        }

        private void Run()
        {
            if (!resetEvent.WaitOne(0) || IsRunning)
            {
                resetEvent.Set();
                return;
            }
            //TODO: Run the task
            tokenSource = new CancellationTokenSource();
            var task = Task.Run(() =>
            {
                IsRunning = true;
                var num = 0;
                while (true)
                { 
                    
                    TaskRunConent = DateTime.Now.ToString("HH:mm:ss");
                    resetEvent.WaitOne();
                    num++;
                    if (tokenSource.IsCancellationRequested)
                    {
                        IsRunning = false;
                        break;
                    }
                }
            }, tokenSource.Token);
            // 等待task完成或取消
            //task.Wait();
            

            task.ContinueWith(t =>
            {
                TaskRunConent = "时间不在运转...";
            });

        }

        private void Pause()
        {
            //TODO: Pause the task
            //TaskRunConent = "Task is paused...";
            resetEvent.Reset();
            
        }

        private void Cancel()
        {
            //TODO: Cancel the task
            //TaskRunConent = "Task is canceled...";
            tokenSource.Cancel();
        }

        private void Continue()
        {
            //TODO: Continue the task
            //TaskRunConent = "Task is continued...";
            resetEvent.Set();
        }

    }
}
